var { Builder, By, until } = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var firefox = require('selenium-webdriver/firefox')
var axios = require('axios');
var path = require('path');
var fs = require('fs');

// var driver = new Builder()
//     .forBrowser('chrome')
//     .setFirefoxService(new chrome.ServiceBuilder('./'))
//     .setChromeOptions(new chrome.Options().headless())
//     .build();

var driver = new Builder()
    .forBrowser('firefox')
    .setFirefoxService(new firefox.ServiceBuilder("./geckodriver.exe"))
    .setFirefoxOptions(new firefox.Options().headless())
    .build();
/**
 * 保存百度图片
 * @param {String} keyWord 搜索关键字
 * @param {Number} count 需要保存的数量
 * @param {String} savePath 保存的本地路径
 */
async function saveImages(keyWord, count, savePath) {
    driver.get('https://image.baidu.com');
    driver.findElement(By.id('kw')).sendKeys(keyWord);
    driver.findElement(By.xpath('//*[@id="homeSearchForm"]/span[2]/input')).click();

    let ele = await driver.wait(until.elementLocated(By.id('resultInfo')), 100000)
    let text =  await ele.getText()
    console.log('text ', text)

    let list = await driver.findElements(By.className('imgitem'))
    console.log('length ', list.length)
    // 滚动达到指定的数量
    // while(list.length < count) {
    //     let lastItem = list[list.length - 1]
    //     let lastLength = list.length
    //     const actions = driver.actions({async: true});
    //     // Performs mouse move action onto the element
    //     await actions.move({origin:lastItem}).perform();
    //     await driver.wait(async () => {
    //         list = await driver.findElements(By.className('imgitem'))
    //         return list.length > lastLength
    //     }, 5000)
    //     console.log('length ', list.length)
    // }
    // 获取所有图片地址
    let imgList = []
    for(let i = 0; i < count; i ++) {
        if (list[i]) {
            let url = await list[i].getAttribute('data-objurl')
            imgList.push(url)
        }
        
        // console.log('url ', url)
    }
    console.log('imgList :>> ', imgList.length);
    // 保存图片
    for(let i = 0; i < count; i ++) {
        if (imgList[i]) {
            // TODO 判断目录是否存在，不存在就创建
            let imgPath = path.resolve(savePath + `img${i}.jpg`)
            const writer = fs.createWriteStream(imgPath)
            const response = await axios({
                url: imgList[i],
                method: 'GET',
                responseType: 'stream'
            });
            response.data.pipe(writer)
        }
    }
    console.log('END!!!') 
}

saveImages('美女', 50, 'C:\\Users\\duan\\Desktop\\test\\')